 package com.cdty.chess.service.impl;

import com.cdty.chess.model.Cuser;
import com.cdty.chess.service.CuserService;
import com.cdty.chess.util.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class CuserServiceImpl implements CuserService {

    @Autowired
    NamedParameterJdbcTemplate template;


    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public String addCuser(Cuser cuser) {

        cuser.setPassword(passwordEncoder.encode(cuser.getPassword()));
        //查询是否存在用户名
        String sql = """
                    select * from cuser where uname = :uname
                """;
        MapSqlParameterSource param = new MapSqlParameterSource();
        param.addValue("uname", cuser.getUname());
        List<Cuser> result = template.query(sql, param, new BeanPropertyRowMapper<>(Cuser.class));
        if (result != null && result.size() > 0) {
            return "error";
        }
        // 查询主键
        String addsql = """
                    insert into cuser (
                        uname, password,sex,phone,
                        email,hpicture,create_time,
                        balance, master,master_level,
                        is_use
                    )values(
                        :uname,:password,:sex,:phone,
                        :email,:hpicture,now(),
                        0,false,'0',
                         true
                    )
                """;
        try {
            int update = this.template.update(addsql, new MapSqlParameterSource("uname", cuser.getUname())
                            .addValue("password", cuser.getPassword())
                            .addValue("sex", cuser.getSex())
                            .addValue("phone", cuser.getPhone())
                            .addValue("email", cuser.getEmail())
                            .addValue("hpicture", cuser.getHpicture())
                            .addValue("create_time", cuser.getCreate_time())
                            .addValue("balance", cuser.getBalance())
                            .addValue("master_level", cuser.getMaster_level())
                            .addValue("is_use", cuser.getIs_use())
                    );
            return "success";
        } catch (Exception e) {
            e.getStackTrace();
        }
        return "";
    }

    @Override
    public String updateCuser(Cuser cuser) {
        String message = "";
        String sql = """
                    update cuser set uid = :uid 
                """;
        MapSqlParameterSource param = new MapSqlParameterSource();
        if (StringUtils.hasText(cuser.getUname())) {
            sql += " , uname = :uname";
            param.addValue("uname", cuser.getUname());
            message = "修改成功";
        }
        if (StringUtils.hasText(cuser.getPassword())) {
            sql += " , password = :password";
            param.addValue("password", cuser.getPassword());
            message = "修改成功";
        }
        if (StringUtils.hasText(cuser.getUnumber())) {
            sql += " , unumber = :unumber";
            param.addValue("unumber", cuser.getUnumber());
            message = "修改成功";
        }
        if (StringUtils.hasText(cuser.getCard_name())) {
            sql += " , card_name = :card_name";
            param.addValue("card_name", cuser.getCard_name());
            message = "修改成功";
        }
        if (StringUtils.hasText(cuser.getPhone())) {
            sql += " , phone = :phone";
            param.addValue("phone", cuser.getPhone());
            message = "修改成功";
        }
        if (StringUtils.hasText(cuser.getEmail())) {
            sql += " , email = :email";
            param.addValue("email", cuser.getEmail());
            message = "修改成功";
        }
        if (cuser.getBalance() != null) {
            sql += " , balance = balance+:balance";
            param.addValue("balance", cuser.getBalance());
            message = "用户余额修改成功";
        }
        if (cuser.getBalance() != null) {
            sql += " , scores = scores+:balance";
            param.addValue("balance", cuser.getBalance());
            message = "用户总积分修改成功";
        }
        if (cuser.getIs_use() != null) {
            sql += " , is_use = :is_use";
            param.addValue("is_use", cuser.getIs_use());
            message = "该用户状态已更新";
        }
        if (cuser.getMaster() != null) {
            sql += " , master = :master";
            param.addValue("master", cuser.getMaster());
            message = "该用户权限已更新";
        }
        param.addValue("uid", cuser.getUid());
        sql += " where uid = :uid";
        try {
            //判断是否充值还是提现
            if(cuser.getBalance()!=null && cuser.getBalance().compareTo(new BigDecimal(0))==1){
                //更新admin总分
                String upbalance = "UPDATE cuser SET balance = balance-:scoreSum  WHERE uname = 'admin'";
                template.update(upbalance, new MapSqlParameterSource("scoreSum", cuser.getBalance()) );
                //同时更新记录表
                String rsql = " insert into record_info (id,create_time,score,btype,uid,uname ) values(:id,now(),:score,:btype,:uid,:uname )";
                String id = UUID.randomUUID().toString(); // 生成 UUID.
                int cou = template.update(rsql, new MapSqlParameterSource("id", id)
                        .addValue("uid",cuser.getUid())
                        .addValue("uname",cuser.getUname())
                        .addValue("score",cuser.getBalance())
                        .addValue("btype",0) //0表示充值
                );
            }
            this.template.update(sql, param);
            return message;
        } catch (Exception e) {
            e.getStackTrace();
        }
        return null;
    }

    @Override
    public List<Cuser> getCuser(Cuser cuser) {
        String sql = """
                    select * from cuser where 1=1
                """;
        MapSqlParameterSource param = new MapSqlParameterSource();

        if (StringUtils.hasText(cuser.getUname())) {
            sql += " and uname like concat('%',:uname,'%') ";
            param.addValue("uname", cuser.getUname());
        }
        if (StringUtils.hasText(cuser.getUid())) {
            sql += " and uid =:uid ";
            param.addValue("uid", cuser.getUid());
        }
        List<Cuser> result = template.query(sql, param, new BeanPropertyRowMapper<>(Cuser.class));
        return result;
    }

    @Override
    public String changePass(Cuser cuser) {
        if(StringUtils.hasText(cuser.getOldPassword())){
            String sql = """
                    SELECT * from cuser c where uid =:uid and is_use = true
                """;
            MapSqlParameterSource param = new MapSqlParameterSource();
            if(StringUtils.hasText(cuser.getUid())){
                param.addValue("uid",cuser.getUid());
            }
            List<Cuser> result = template.query(sql, param, new BeanPropertyRowMapper<>(Cuser.class));
            if(result!=null && result.size()==1&&passwordEncoder.matches(cuser.getOldPassword(), result.get(0).getPassword())){
                cuser.setPassword(passwordEncoder.encode(cuser.getPassword()));
                try {
                    String message = this.updateCuser(cuser);
                    return "success";
                } catch (Exception e) {
                    e.getStackTrace();
                    return e.getMessage();
                }
            }else{
                return "原密码错误";
            }
        }else {
            cuser.setPassword(passwordEncoder.encode(cuser.getPassword()));
            try {
                String message = this.updateCuser(cuser);
                return "success";
            } catch (Exception e) {
                e.getStackTrace();
                return e.getMessage();
            }
        }
    }

    @Override
    public String updateAdmin(BigDecimal score) {
            //更新admin总分
            String upbalance = "UPDATE cuser SET balance = :score  WHERE uname = 'admin'";
            template.update(upbalance, new MapSqlParameterSource("score", score) );
        return "success";
    }

    @Override
    public Map<String, Object> getCuserPage(String name, Integer page, Integer size) {
        Map<String, Object> result = new HashMap<>();
        MapSqlParameterSource parameters = new MapSqlParameterSource();

        int offset = (page - 1) * size;
        String sql = "SELECT * FROM cuser where 1=1 and master_level !='1' ";
        String countsql = "SELECT count(1) total FROM cuser where 1=1 and master_level !='1' ";
        if (StringUtils.hasText(name)) {
            sql += " and uname like concat('%',:name,'%') ";
            countsql += " and uname like concat('%',:name,'%') ";
            parameters.addValue("name", name);
        }
        sql += " LIMIT :size OFFSET :offset";
        parameters.addValue("size", size);
        parameters.addValue("offset", offset);
        List<Map<String, Object>> mapList = template.queryForList(sql, parameters);
        Map<String, Object> countMap = template.queryForMap(countsql, parameters);
        result.put("total", countMap.get("total"));
        result.put("dataList", mapList);
        return result;
    }
}
